<template>
  <el-dialog
    top="30px"
    width="1000px"
    title="项目受理"
    append-to-body
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="beforeClose"
  >
    <div v-loading="loading">
      <el-form
        label-width="100px"
        :model="editData"
        :rules="rules"
        ref="form"
        label-position="left"
      >
        <el-form-item label="贷款银行" prop="bank_id">
          <select-class-bank
            class="form-control-ml"
            clearable
            placeholder="请选择（非必填）"
            :product-id="formData.project_type_id"
            v-model="editData.bank_id"
            @select="handleSelectBankOrg"
          ></select-class-bank>
        </el-form-item>
        <el-form-item label="担保机构" prop="service_id">
          <select-org-credit
            class="form-control-ml"
            clearable
            placeholder="请选择（非必填）"
            :product-id="formData.project_type_id"
            v-model="editData.service_id"
            @select="handleSelectCreditOrg"
          ></select-org-credit>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn-long" @click="submit" :loading="saveLoading">
            受理
          </el-button>
          <el-button type="danger" class="btn-long" @click="handleReject" :loading="saveLoading">
            拒绝
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import SelectOrgCredit from '@/gov/components/select/SelectOrgCredit'
import SelectClassBank from '@/gov/views/bus/track/recom/components/SelectClassBanks'
import { mapGetters } from 'vuex'
export default {
  components: {
    SelectClassBank,
    SelectOrgCredit,
  },
  props: {
    tableId: String,
    visible: Boolean,
    formData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      saveLoading: false,
      loading: false,
      rules: {},
      editData: {
        service_id: '',
        service_name: '',
        bank_id: '',
        bank_name: '',
        bank_type: '',
      },
      relatedData: {},
    }
  },
  computed: {
    ...mapGetters(['user']),
    tableName() {
      return +(this.formData?.credit_type || '') === 1 ? 'credit_industrial' : 'credit_direct'
    },
  },
  watch: {
    formData: {
      handler: function () {
        Object.keys(this.editData).forEach(key => {
          this.editData[key] = this.formData[key]
        })
        if (this.formData.credit_id) {
          this.getRelateData()
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getRelateData() {
      const params =
        +this.formData.credit_type === 1
          ? {
              'credit_industrial_id.eq': this.formData.credit_id,
            }
          : {
              'credit_direct_id.eq': this.formData.credit_id,
            }
      this.loading = true
      this.$api
        .getData('credit', 'customer_related', params)
        .then(res => {
          this.relatedData = res.data?.[0] ?? {}
          Object.keys(this.editData).forEach(key => {
            this.editData[key] = this.relatedData[key] || this.editData[key]
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    async submit() {
      this.saveLoading = true
      const {
        credit_id: creditId,
        credit_type: creditType,
        statusLabel,
        statusStyle,
        idCard,
        createTime,
        ...rest
      } = this.formData
      await this.$api.updateData(this.$serviceName, this.tableName, this.tableId, {
        bank_id: this.editData.bank_id,
        bank_name: this.editData.bank_name,
        service_id: this.editData.service_id,
        service_name: this.editData.service_name,
        is_approval: 1,
      })
      // 数据分类：专班、新农直报
      if (+creditType === 1) {
        rest.credit_industrial_id = creditId
      } else {
        rest.credit_direct_id = creditId
      }
      if (!this.relatedData.customer_related_id) {
        this.$api
          .addData('credit', 'customer_related', {
            ...rest,
            credit_type: creditType,
            recommend_status: 1,
            is_approval: 0,
            submit_type: 1,
            service_id: this.editData.service_id,
            service_name: this.editData.service_name,
            bank_id: this.editData.bank_id,
            bank_name: this.editData.bank_name,
            bank_type: this.editData.bank_type,
          })
          .then(res => {
            this.$message.success('受理成功')
            this.beforeClose()
            this.$emit('success', res)
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || '提交失败，请重试！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.$api
          .updateData('credit', 'customer_related', this.relatedData.customer_related_id, {
            ...this.relatedData,
            ...rest,
            credit_type: creditType,
            confuse_status: null,
            confuse_des: '',
            recommend_status: 1,
            is_approval: 0,
            submit_type: 1,
            service_id: this.editData.service_id,
            service_name: this.editData.service_name,
            bank_id: this.editData.bank_id,
            bank_name: this.editData.bank_name,
            bank_type: this.editData.bank_type,
          })
          .then(res => {
            this.$message.success('受理成功')
            this.beforeClose()
            this.$emit('success', res)
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || '提交失败，请重试！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    handleReject() {
      if (!this.tableId) {
        return
      }

      this.$prompt('请输入拒绝说明', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入拒绝说明' : true),
      }).then(({ value }) => {
        this.$api
          .updateData(this.$serviceName, this.tableName, this.tableId, {
            is_approval: 2,
            confuse_person: this.user.realName,
            confuse_des: value,
            confuse_time: this.$utils.dateFormat(new Date()),
          })
          .then(() => {
            if (this.relatedData.customer_related_id) {
              this.$api
                .updateData('credit', 'customer_related', this.relatedData.customer_related_id, {
                  confuse_person: this.user.realName,
                  confuse_status: 3,
                  confuse_des: value,
                  confuse_time: this.$utils.dateFormat(new Date()),
                })
                .catch(err => {
                  this.$message.error(err?.data?.error_description || '提交失败，请重试！')
                })
            }
            this.$message.success('已拒绝！')
            this.$emit('success', true)
            this.beforeClose()
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || '提交失败，请重试！')
          })
      })
    },
    handleSelectCreditOrg(org) {
      this.editData.service_name = org.agency_name
    },
    handleSelectBankOrg(org) {
      this.editData.bank_name = org.agency_name
      this.editData.bank_type = org.agency_type_sub
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style lang="scss" scoped></style>
